package DAO;


import Entities.DoeBookEntity;
import Entities.ShoppingTrolleyEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.ArrayList;
import java.util.List;

public class ShpTrolleyDao extends HibernateDaoSupport
{
    //添加一条记录到购物车数据表
    public String addRecord(String user_name, String bookId)
    {
        ShoppingTrolleyEntity shoppingTrolleyEntity = new ShoppingTrolleyEntity();
        if(user_name != null)
            shoppingTrolleyEntity.setUserName(user_name);
        if(bookId != null)
            shoppingTrolleyEntity.setBookId(bookId);

        List<ShoppingTrolleyEntity> shpTrolleyList = (List<ShoppingTrolleyEntity>) this.getHibernateTemplate().find("from ShoppingTrolleyEntity s where s.userName=? and s.bookId=?",user_name,bookId);
        if(shpTrolleyList.size()==0)
        {
            //若购物车数据表中不存在该记录，则添加
            this.getHibernateTemplate().save(shoppingTrolleyEntity);
            return "success";
        }
        else if(shpTrolleyList.size()>0)
        {
            return "exist already";  //已经存在于数据表中
        }
        return "failure";
    }

    //返回某个用户的购物车列表
    public List<DoeBookEntity> returnShpTrolleyList(String user_name)
    {

//        String hql = "from DoeBookEntity b, ShoppingTrolleyEntity s where b.bookId=s.bookId and s.userName="+user_name;
//        Query query= getSession().createQuery(hql);
//        List list = query.list();
//        return null;

        String sql = "select d.* from doe_book d, shoppingTrolley s where d.book_id=s.bookId";
        List<DoeBookEntity> bookEntities = (List<DoeBookEntity>) getSession().createSQLQuery(sql).list();

        return bookEntities;

    }

    //继承了HibernateDaoSupport类获取Session的方法
    public Session getSession()
    {
        return this.getHibernateTemplate().getSessionFactory().getCurrentSession();
    }
}